//
//  luoerOauthViewController.swift
//  WeiBoStudy
//
//  Created by luoerliu on 16/5/14.
//  Copyright © 2016年 刘文平. All rights reserved.
//

import UIKit
import SVProgressHUD
let oauthURLString = "https://api.weibo.com/oauth2/authorize"
/// 申请应用时分配的AppKey
let client_id = "1035372196"
/// 授权回调地址
let redirect_uri = "http://www.baidu.com/"
/// 申请应用时分配的AppSecret
let client_secret = "1dd6bfd4449e63a120605360c692d111"
class luoerOauthViewController: UIViewController {
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.orangeColor()
//        设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.title = "登录"
          self.loadWebView()
    }
//    导航栏按钮的点击方法
    @objc private func autoFill()
    {
        let jsString = "document.getElementById('userId').value='15920587087';document.getElementById('passwd').value='lwp5261314';"
        
        // 使用WebView执行JS代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    @objc private func close()
    {
         SVProgressHUD.dismiss()
          dismissViewControllerAnimated(true, completion: nil)
    }
// 使用webview加载出界面
    func loadWebView()
    {
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
//        加载提示器
       SVProgressHUD.showWithStatus("正在加载")
    }
//  懒加载出webview
    private  lazy var webView:UIWebView = UIWebView()
}
//WebView的代理方法
extension luoerOauthViewController: UIWebViewDelegate {
    /// webView加载完成调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
//    网页开始加载的时候调用这个方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        返回的回调地址
        let url = request.URL!
        if !url.absoluteString.hasPrefix(redirect_uri)
        {
//       如果加载的页面不是授权回调地址就让他加载，不去拦截
            return true
        }else
        {
            let query = url.query!
            let codeString = "code="
//            判断如果返回的地址是以code=开头的，则说明点击的是授权按钮
            if query.hasPrefix(codeString)
            {
//                  从query中截取code的值
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                print("code = \(code)")
                luoerUserAccountViewModel.sharedinstance.loadAccessToken(code, callback: { (error) -> () in
                    if error != nil
                    {
//                       出现了错误
                        SVProgressHUD.showErrorWithStatus("网络异常")
                        // 延迟一秒关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
            })
                    }else
            {
//                        没有错误
//                        self.close()
//                跳转到欢迎界面
                let appDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
                appDelegate.switchRootViewController(luoerWelcomeViewController())
            }
            })
                    }else
            {
//                点击的是取消按钮
                close()
            }
            return false
        }
    }
}

